/**
 * 图片模型
 * @param app
 */
module.exports = app => {
  const { STRING, INTEGER, BOOLEAN, DATE, BIGINT } = app.Sequelize;

  const Image = app.model.define('sys_images', {
    id: {
      type: BIGINT,
      primaryKey: true,
      comment: '图片ID',
    },
    fileName: {
      type: STRING(255),
      allowNull: false,
      comment: '文件名',
      field: 'file_name',
    },
    filePath: {
      type: STRING(255),
      allowNull: false,
      comment: '文件路径',
      field: 'file_path',
    },
    fileSize: {
      type: INTEGER,
      allowNull: false,
      comment: '文件大小(字节)',
      field: 'file_size',
    },
    fileType: {
      type: STRING(50),
      allowNull: false,
      comment: '文件类型',
      field: 'file_type',
    },
    url: {
      type: STRING(255),
      allowNull: false,
      comment: '访问URL',
    },
    uploadTime: {
      type: DATE,
      allowNull: false,
      comment: '上传时间',
      field: 'upload_time',
    },
    status: {
      type: BOOLEAN,
      defaultValue: true,
      comment: '状态：true启用，false禁用',
    },
    createTime: {
      type: DATE,
      allowNull: false,
      comment: '创建时间',
      field: 'create_time',
      defaultValue: app.Sequelize.NOW,
    },
    updateTime: {
      type: DATE,
      allowNull: false,
      comment: '更新时间',
      field: 'update_time',
      defaultValue: app.Sequelize.NOW,
    },
    category: {
      type: STRING(100),
      allowNull: true,
      comment: '图片分类',
    },
    tags: {
      type: STRING(500),
      allowNull: true,
      comment: '图片标签，JSON格式',
      get() {
        const tags = this.getDataValue('tags');
        return tags ? JSON.parse(tags) : [];
      },
      set(value) {
        this.setDataValue('tags', JSON.stringify(value));
      },
    },
    uploadedBy: {
      type: STRING(100),
      allowNull: true,
      comment: '上传人用户名',
      field: 'uploaded_by',
    },
    uploadedById: {
      type: BIGINT,
      allowNull: true,
      comment: '上传人用户ID',
      field: 'uploaded_by_id',
    },

  });

  // 在创建前生成雪花ID
  Image.beforeCreate((image) => {
    const SnowflakeUtil = require('../utils/snowflake');
    image.id = SnowflakeUtil.generateSnowflakeId();
  });

  // 自定义toJSON方法，避免字段重复
  Image.prototype.toJSON = function () {
    const values = Object.assign({}, this.get());

    // 移除重复的下划线字段
    delete values.file_name;
    delete values.file_path;
    delete values.file_size;
    delete values.file_type;
    delete values.upload_time;
    delete values.create_time;
    delete values.update_time;
    /* delete values.uploaded_by;
    delete values.uploaded_by_id; */

    return values;
  };

  return Image;
};
